<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="旧密码" path="oldPassword">
          <n-input type="password" v-model:value="formValue.oldPassword" placeholder="请输入旧密码" />
        </n-form-item>
        <n-form-item label="新密码" path="newPassword">
          <n-input type="password" v-model:value="formValue.newPassword" placeholder="请输入新密码" />
        </n-form-item>
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input type="password" v-model:value="formValue.confirmPassword" placeholder="请输入确认密码" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">修改密码</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { updatePassword } from '@/api/system/admin';
  import { ResultEnum } from '@/enums/httpEnum';
  import { CURRENT_USER } from '@/store/mutation-types';
  import { storage, createStorage } from '@/utils/Storage';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { PageEnum } from '@/enums/pageEnum';
  const Storage = createStorage({ storage: localStorage });

  const rules = {
    oldPassword: {
      required: true,
      min: 6,
      message: '旧密码不能为空且长度不能少于6位',
      trigger: 'blur',
    },
    newPassword: {
      required: true,
      min: 6,
      message: '新密码不能为空且长度不能少于6位',
      trigger: 'blur',
    },
    confirmPassword: {
      required: true,
      min: 6,
      trigger: 'blur',
      validator: (rule, value) => {
        if (!value) {
          return new Error('请确认新密码');
        }
        if (value.length < 6) {
          return new Error('确认密码长度不能少于6位');
        }
        if (value !== formValue.newPassword) {
          return new Error('两次输入的密码不一致');
        }
        return true;
      }
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();
  const router = useRouter();
  const userStore = useUserStore();

  const formValue = reactive({
    ...Storage.get(CURRENT_USER, {}),
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  function formSubmit() {
    console.log('formSubmit', formValue);
    formRef.value.validate(async (errors) => {
      if (!errors) {
        //message.success('验证成功');
        const response = await updatePassword(formValue);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          // 密码修改成功后退出登录
          setTimeout(() => {
            // 先清空标签页状态，再执行退出登录
            const tabsViewStore = useTabsViewStore();
            // 直接清空标签页数组，而不仅仅是调用closeAllTabs
            tabsViewStore.tabsList = [];
            // 移除标签页本地存储
            localStorage.removeItem('TABS_ROUTES');
            
            userStore.logout().then(() => {
              router.replace({
                name: PageEnum.BASE_LOGIN_NAME
              }).finally(() => location.reload());
            });
          }, 1000);
        } else {
          message.error(msg);
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
      // 清空输入框内容
      formValue.oldPassword = '';
      formValue.newPassword = '';
      formValue.confirmPassword = '';
      // 重置表单验证状态 - 使用 Naive UI 表单的正确重置方法
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    });
  }
</script>
